﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System;
using ZX.Web.UI.Controls;
using ZX.SYS.Bussiness;
using System.Data;
using ZX.BLL.Extend;
using ZX.EHR.Library;
using ZX.DBModule;
using ZX.BLL;
using System.Web.Security;
using ZX.SYS.Library;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Data.SqlClient;

using Newtonsoft.Json;

namespace ZX.WebApp.Message
{
    public partial class SendMag : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnsendOnClick(object sender, EventArgs e)
        {
            //内容
            string messa = txtMODEL.Value;
            //消息标题
            string title = txtTitle.Value;if (title.Length > 25)
            {
                Labmes.Text = "字数限制：短信标题字数超过25，请裁剪后发送！";
                return;
            }
            else if (messa.Length > 500)
            {
                Labmes.Text = "字数限制：短信内容字数超过500，请裁剪后发送！";
                return;
            }

            #region 赋值
            ZX.EHR.Library.DatUser u = (Session["User"] as ZX.EHR.Library.DatUser);
            ///发送人编号
            Guid AddUser = u.UserID;
            ///发送人名称
            string createPeopleName = u.UName;
            ///发送方式
            string sendMode = ddlSendmode.SelectedValue;
            //接收人的id【要转换成datUser的userId】
            string ReceiverIds = PM.Value;
            //接收人名称【文本框】
            string recevePeopleName = txtPM.Value;
            #endregion

            //选择对象[群组、组织架构、群组成员]
            string op = selectOption.SelectedValue;
            MQproccess mqp = new MQproccess();
            string back = "";

            #region 短信发送的逻辑处理
            if (op == "2" && ReceiverIds != "") //群组发送
            {
                //重置接收人名称
                //recevePeopleName = "";

                DataTable dt = mqp.GetUserType(ReceiverIds);
                DataRow[] d = dt.Select();
                if (d.Length > 0)//群组中的人数大于0，代表有人存在
                {
                    //重置接收人的id
                    ReceiverIds = "";
                    for (int i = 0; i < d.Length; i++)
                    {
                        //群组内的人有用户编号，就给他发送短信
                        if (d[i]["UserID"].ToString() != "" && d[i]["UserID"].ToString() != null)
                        {
                            ReceiverIds += d[i]["UserID"].ToString() + ",";
                        }
                    }
                }
                else
                {
                    back += "该组无成员，无法发送!";
                    recevePeopleName = "";//后面不再执行
                }
            }
            else if ((op == "3" || op == "0") && recevePeopleName != "")   //当选择群组内的人员时，只取姓名
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                //<李丽红>13802239336,<陈星兰>13510029932
                string[] str = recevePeopleName.TrimEnd(',').Split(',');
                for (int i = 0; i < str.Length; i++)
                {
                    string s = str[i];
                    sb.Append(s.Substring(s.IndexOf('<') + 1, s.LastIndexOf('>')-1) + ",");
                    //sb.Append("insert into DatSysNewsInfo(Nid,recevePeopleID) values(@Nid,'" + Guid.Parse(str[i]) + "');");
                }
                //重置接收人名称
                recevePeopleName = sb.ToString().TrimEnd(',');
            }
            #endregion

            #region 添加操作
            if (recevePeopleName != "" && recevePeopleName != string.Empty)
            {
                try
                {
                    #region 数据库代码
                    ///定义字符串
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append("declare @Nid uniqueidentifier;set @Nid=NEWID();");
                    sb.Append("insert into DatSysNews(ID,AddUser,createPeopleName,recevePeopleName,title,content,sendMode)");
                    sb.Append("values(@Nid,@AddUser,@createPeopleName,@recevePeopleName,@title,@content,@sendMode);");
                    //sb.Append("values(@Nid,'" + AddUser + "','" + createPeopleName + "','" + recevePeopleName + "','" + title + "','" + messa + "','" + sendMode + "');");
                    //添加子表信息
                    string[] str = ReceiverIds.TrimEnd(',').Split(',');

                    System.Text.StringBuilder userIds = new System.Text.StringBuilder();
                    for (int i = 0; i < str.Length; i++)
                    {
                        sb.Append("insert into DatSysNewsInfo(Nid,recevePeopleID) values(@Nid,@recevePeopleID" + i + ");");
                        //sb.Append("insert into DatSysNewsInfo(Nid,recevePeopleID) values(@Nid,'" + Guid.Parse(str[i]) + "');");

                        userIds.Append("'" + str[i]+"',");
                    }
                    
                    //打开数据库
                    string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ToString();
                    using (SqlConnection conn = new SqlConnection(connString))
                    {
                        conn.Open();

                        #region 获取DatUser_Mobile中的Key，以后DatUser_Mobile有数据了启用查询
                        string sql = "select EmpId from DatUser where userid in (" + userIds.ToString().TrimEnd(',') + ")";
                        SqlCommand comm = new SqlCommand(sql, conn);
                        SqlDataReader dr = comm.ExecuteReader();
                        //List<DatUser_Mobile> list = new List<DatUser_Mobile>();

                        int FieldCount = 0;

                        System.Text.StringBuilder DatSysNewsPushStr = new System.Text.StringBuilder();
                        while (dr.Read())
                        {
                            FieldCount = FieldCount + 1;

                            DatSysNewsPushStr.Append("insert into [DatSysNewsPush](mobileID,mobiletype,Title) values('" + dr["EmpID"].ToString() + "',0,'" + title + "');");
                        
                        }
                        dr.Close();

                        if (FieldCount < str.Length)
                        {
                            back += "部分人员的设备信息为空<br/>将无法收到手机短信<br/>";
                        }
                        sb.Append(DatSysNewsPushStr.ToString().TrimEnd(','));

                        //back += "SQL语句为:" + sb.ToString() + "<br/>";
                        #endregion

                        SqlCommand com = new SqlCommand(sb.ToString(), conn);
                        com.Parameters.Add("AddUser", SqlDbType.UniqueIdentifier);
                        com.Parameters["AddUser"].Value = AddUser;  ///发送人userid
                        com.Parameters.Add("createPeopleName", SqlDbType.VarChar, 50);
                        com.Parameters["createPeopleName"].Value = createPeopleName;    ///发送人的名字

                        com.Parameters.Add("recevePeopleName", SqlDbType.VarChar, 8000);
                        com.Parameters["recevePeopleName"].Value = recevePeopleName;    ///接收人的名字
                        com.Parameters.Add("title", SqlDbType.VarChar, 50);
                        com.Parameters["title"].Value = title;  ///标题

                        com.Parameters.Add("content", SqlDbType.VarChar, 500);
                        com.Parameters["content"].Value = messa;    ///内容
                        com.Parameters.Add("sendMode", SqlDbType.VarChar, 50);
                        com.Parameters["sendMode"].Value = sendMode;    ///发送方式

                        //给字表的参数赋值
                        for (int i = 0; i < str.Length; i++)
                        {
                            com.Parameters.Add("recevePeopleID" + i, SqlDbType.UniqueIdentifier);
                            com.Parameters["recevePeopleID" + i].Value = Guid.Parse(str[i]);
                        }

                        int wolf = com.ExecuteNonQuery();
                        if (wolf > 0)
                        {
                            back += "发送成功！<br/>";
                            Labmes.Enabled = false;
                            btnsend.Enabled = false;
                        }
                        else
                        {
                            back += "发送失败！<br/>";
                        }
                    }
                    #endregion
                }
                catch (System.Exception ex)
                {                    
                    throw ex;
                }
            }
            #endregion
            Labmes.Text = back;
        }
    }
}